package com.yuchen.learning.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileController {

    // 可通过 application.properties 配置上传目录
    @Value("${file.upload-dir:uploads/}")
    private String uploadDir;

    @PostMapping("/api/file/upload")
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        if (file.isEmpty()) {
            result.put("error", "文件不能为空");
            return result;
        }
        try {
            // 1. 获取原始文件名和扩展名
            String originalName = file.getOriginalFilename();
            String ext = "";
            if (originalName != null && originalName.contains(".")) {
                ext = originalName.substring(originalName.lastIndexOf("."));
            }
            // 2. 防止重名，拼 UUID
            String newFileName = UUID.randomUUID() + ext;
            // 3. 本地上传路径（可自定义）
            File dest = new File(uploadDir, newFileName);
            // 自动创建目录
            dest.getParentFile().mkdirs();
            file.transferTo(dest);
            // 4. 访问路径（假设 Spring Boot 静态资源映射 /uploads/**）
            String url = "/uploads/" + newFileName;
            result.put("url", url);
        } catch (IOException e) {
            result.put("error", "上传失败");
        }
        return result;
    }
}